// ============================================================================
// 用户数据管理页面
// ============================================================================

import React, { useState, useEffect } from 'react'
import { dataService } from '../services/data-service'
import { useNotifications } from '../hooks/use-notifications'
import { logger } from '../utils/logger'

/**
 * 用户数据统计信息
 */
interface UserDataStats {
  total: number
  today: number
  thisWeek: number
  thisMonth: number
  vipUsers: number
  verifiedUsers: number
  avgFollowers: number
  topUsers: Array<{ nickname: string; followersCount: number }>
}

/**
 * 用户数据项
 */
interface UserDataItem {
  id: string
  uid: string
  nickname: string
  avatar?: string
  isVip: boolean
  followersCount: number
  followingCount: number
  statusesCount: number
  description?: string
  location?: string
  verifiedType?: number
  verifiedReason?: string
  isVerified: boolean
  lastUpdated?: Date
  createdAt: Date
  updatedAt: Date
}

/**
 * 用户数据管理页面组件
 */
export const UserDataPage: React.FC = () => {
  const [stats, setStats] = useState<UserDataStats | null>(null)
  const [userData, setUserData] = useState<UserDataItem[]>([])
  const [loading, setLoading] = useState(true)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize] = useState(20)
  const [totalCount, setTotalCount] = useState(0)
  const [searchKeyword, setSearchKeyword] = useState('')
  const [filterType, setFilterType] = useState<'all' | 'vip' | 'verified' | 'normal'>('all')
  const [sortBy, setSortBy] = useState<'createdAt' | 'followersCount' | 'statusesCount'>('createdAt')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')
  const { showError } = useNotifications()

  // 加载数据
  useEffect(() => {
    loadData()
  }, [currentPage, searchKeyword, filterType, sortBy, sortOrder])

  /**
   * 加载所有数据
   */
  const loadData = async () => {
    try {
      setLoading(true)
      await Promise.all([
        loadStats(),
        loadUserData()
      ])
    } catch (error) {
      logger.error('加载数据失败', error)
      showError('加载数据失败', `${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  /**
   * 加载统计信息
   */
  const loadStats = async () => {
    try {
      const statsData = await dataService.getUserDataStats()
      setStats(statsData)
    } catch (error) {
      logger.error('加载统计信息失败', error)
      throw error
    }
  }

  /**
   * 加载用户数据列表
   */
  const loadUserData = async () => {
    try {
      const result = await dataService.getUserDataList({
        page: currentPage,
        pageSize,
        keyword: searchKeyword,
        filterType,
        sortBy,
        sortOrder
      })
      setUserData(result.data)
      setTotalCount(result.total)
    } catch (error) {
      logger.error('加载用户数据失败', error)
      throw error
    }
  }

  /**
   * 搜索处理
   */
  const handleSearch = (keyword: string) => {
    setSearchKeyword(keyword)
    setCurrentPage(1)
  }

  /**
   * 筛选处理
   */
  const handleFilter = (type: 'all' | 'vip' | 'verified' | 'normal') => {
    setFilterType(type)
    setCurrentPage(1)
  }

  /**
   * 排序处理
   */
  const handleSort = (field: 'createdAt' | 'followersCount' | 'statusesCount') => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
    } else {
      setSortBy(field)
      setSortOrder('desc')
    }
    setCurrentPage(1)
  }

  /**
   * 格式化数字
   */
  const formatNumber = (num: number): string => {
    if (num >= 10000) {
      return `${(num / 10000).toFixed(1)}万`
    }
    return num.toLocaleString()
  }

  /**
   * 格式化日期
   */
  const formatDate = (date: Date | string): string => {
    const d = new Date(date)
    return d.toLocaleString('zh-CN')
  }

  /**
   * 获取认证类型文本
   */
  const getVerifiedTypeText = (type?: number): string => {
    switch (type) {
      case 1: return '个人认证'
      case 2: return '企业认证'
      case 3: return '媒体认证'
      case 4: return '政府认证'
      case 5: return '其他认证'
      default: return '已认证'
    }
  }

  /**
   * 计算总页数
   */
  const totalPages = Math.ceil(totalCount / pageSize)

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-lg text-gray-600">加载中...</div>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">用户数据管理</h1>
        <div className="flex items-center space-x-4">
          <button
            onClick={loadData}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium"
          >
            {loading ? '加载中' : `刷新数据`}
          </button>
        </div>
      </div>

      {/* 统计卡片 */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-white p-6 rounded-lg border">
            <div className="text-3xl font-bold text-blue-600">
              {formatNumber(stats.total)}
            </div>
            <div className="text-sm text-gray-600">总用户数</div>
          </div>

          <div className="bg-white p-6 rounded-lg border">
            <div className="text-3xl font-bold text-green-600">
              {formatNumber(stats.today)}
            </div>
            <div className="text-sm text-gray-600">今日新增</div>
          </div>

          <div className="bg-white p-6 rounded-lg border">
            <div className="text-3xl font-bold text-purple-600">
              {formatNumber(stats.thisWeek)}
            </div>
            <div className="text-sm text-gray-600">本周新增</div>
          </div>

          <div className="bg-white p-6 rounded-lg border">
            <div className="text-3xl font-bold text-orange-600">
              {formatNumber(stats.thisMonth)}
            </div>
            <div className="text-sm text-gray-600">本月新增</div>
          </div>
        </div>
      )}

      {/* 详细统计信息 */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-white p-4 rounded-lg border">
            <div className="text-lg font-semibold text-gray-900 mb-2">VIP用户</div>
            <div className="text-2xl font-bold text-yellow-600">
              {formatNumber(stats.vipUsers)}
            </div>
            <div className="text-sm text-gray-600">VIP用户数</div>
          </div>

          <div className="bg-white p-4 rounded-lg border">
            <div className="text-lg font-semibold text-gray-900 mb-2">认证用户</div>
            <div className="text-2xl font-bold text-red-600">
              {formatNumber(stats.verifiedUsers)}
            </div>
            <div className="text-sm text-gray-600">认证用户数</div>
          </div>

          <div className="bg-white p-4 rounded-lg border">
            <div className="text-lg font-semibold text-gray-900 mb-2">平均粉丝</div>
            <div className="text-2xl font-bold text-pink-600">
              {formatNumber(stats.avgFollowers)}
            </div>
            <div className="text-sm text-gray-600">平均粉丝数</div>
          </div>
        </div>
      )}

      {/* 搜索和筛选 */}
      <div className="bg-white p-4 rounded-lg border">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
          {/* 搜索框 */}
          <div className="flex-1 max-w-md">
            <input
              type="text"
              placeholder="搜索用户昵称..."
              value={searchKeyword}
              onChange={(e) => handleSearch(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* 筛选按钮 */}
          <div className="flex items-center space-x-2">
            <button
              onClick={() => handleFilter('all')}
              className={`px-3 py-2 text-sm rounded-lg ${filterType === 'all'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
            >
              全部
            </button>
            <button
              onClick={() => handleFilter('vip')}
              className={`px-3 py-2 text-sm rounded-lg ${filterType === 'vip'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
            >
              VIP用户
            </button>
            <button
              onClick={() => handleFilter('verified')}
              className={`px-3 py-2 text-sm rounded-lg ${filterType === 'verified'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
            >
              认证用户
            </button>
            <button
              onClick={() => handleFilter('normal')}
              className={`px-3 py-2 text-sm rounded-lg ${filterType === 'normal'
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
            >
              普通用户
            </button>
          </div>
        </div>
      </div>

      {/* 用户数据列表 */}
      <div className="bg-white rounded-lg border">
        <div className="px-6 py-4 border-b">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-900">用户数据列表</h2>
            <div className="text-sm text-gray-500">
              共 {formatNumber(totalCount)} 个用户
            </div>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  用户信息
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  用户描述
                </th>
                <th
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('followersCount')}
                >
                  粉丝数 {sortBy === 'followersCount' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('statusesCount')}
                >
                  微博数 {sortBy === 'statusesCount' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  用户标签
                </th>
                <th
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
                  onClick={() => handleSort('createdAt')}
                >
                  采集时间 {sortBy === 'createdAt' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {userData.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-8 text-center text-gray-500">
                    暂无数据
                  </td>
                </tr>
              ) : (
                userData.map((user) => (
                  <tr key={user.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4">
                      <div className="flex items-center">
                        <div className="relative h-12 w-12 rounded-full mr-4 flex-shrink-0">
                          {user.avatar ? (
                            <img
                              className="h-12 w-12 rounded-full object-cover"
                              src={user.avatar}
                              alt={user.nickname}
                              onError={(e) => {
                                const target = e.target as HTMLImageElement
                                target.style.display = 'none'
                                const parent = target.parentElement
                                if (parent) {
                                  parent.innerHTML = `
                                    <div class="h-12 w-12 rounded-full bg-gray-200 flex items-center justify-center">
                                      <svg class="h-6 w-6 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
                                      </svg>
                                    </div>
                                  `
                                }
                              }}
                            />
                          ) : (
                            <div className="h-12 w-12 rounded-full bg-gray-200 flex items-center justify-center">
                              <svg className="h-6 w-6 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                                <path fillRule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clipRule="evenodd" />
                              </svg>
                            </div>
                          )}

                          {/* VIP标签 - 头像右上角 */}
                          {user.isVip && (
                            <div className="absolute -top-1 -right-1 h-5 w-5 bg-yellow-400 rounded-full flex items-center justify-center border-2 border-white">
                              <span className="text-xs">👑</span>
                            </div>
                          )}

                          {/* 认证标签 - 头像右下角 */}
                          {user.isVerified && (
                            <div className="absolute -bottom-1 -right-1 h-4 w-4 bg-blue-500 rounded-full flex items-center justify-center border-2 border-white">
                              <svg className="h-2 w-2 text-white" fill="currentColor" viewBox="0 0 20 20">
                                <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                              </svg>
                            </div>
                          )}
                        </div>
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {user.nickname}
                          </div>
                          <div className="text-sm text-gray-500">
                            UID: {user.uid}
                          </div>
                          {user.location && (
                            <div className="text-xs text-gray-400 flex items-center">
                              <svg className="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                <path fillRule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clipRule="evenodd" />
                              </svg>
                              {user.location}
                            </div>
                          )}
                        </div>
                      </div>
                    </td>

                    <td className="px-6 py-4">
                      <div className="max-w-xs">
                        <div className="text-sm text-gray-900 line-clamp-2">
                          {user.description || '暂无描述'}
                        </div>
                      </div>
                    </td>

                    <td className="px-6 py-4">
                      <div className="text-sm text-gray-900">
                        <div className="font-medium">{formatNumber(user.followersCount)}</div>
                        <div className="text-xs text-gray-500">
                          关注: {formatNumber(user.followingCount)}
                        </div>
                      </div>
                    </td>

                    <td className="px-6 py-4">
                      <div className="text-sm font-medium text-gray-900">
                        {formatNumber(user.statusesCount)}
                      </div>
                    </td>

                    <td className="px-6 py-4">
                      <div className="flex flex-wrap gap-1">
                        {/* 粉丝等级标签 */}
                        {user.followersCount >= 1000000 ? (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                            🔥 百万粉丝
                          </span>
                        ) : user.followersCount >= 100000 ? (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                            ⭐ 十万粉丝
                          </span>
                        ) : user.followersCount >= 10000 ? (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            📈 万粉博主
                          </span>
                        ) : null}

                        {/* 活跃度标签 */}
                        {user.statusesCount >= 10000 && (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                            � 高产博主
                          </span>
                        )}

                        {/* 如果没有特殊标签，显示基础信息 */}
                        {user.followersCount < 10000 && user.statusesCount < 10000 && (
                          <span className="text-xs text-gray-500">
                            {user.isVerified ? getVerifiedTypeText(user.verifiedType) : '普通用户'}
                          </span>
                        )}
                      </div>

                      {/* 认证原因 - 单独一行 */}
                      {user.verifiedReason && (
                        <div className="text-xs text-gray-500 mt-1 line-clamp-1" title={user.verifiedReason}>
                          {user.verifiedReason}
                        </div>
                      )}
                    </td>

                    <td className="px-6 py-4 text-sm text-gray-900">
                      <div>{formatDate(user.createdAt)}</div>
                      {user.lastUpdated && (
                        <div className="text-xs text-gray-500">
                          更新: {formatDate(user.lastUpdated)}
                        </div>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* 分页 */}
        {totalPages > 1 && (
          <div className="px-6 py-4 border-t">
            <div className="flex items-center justify-between">
              <div className="text-sm text-gray-700">
                显示第 {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, totalCount)} 条，
                共 {totalCount} 条数据
              </div>

              <div className="flex items-center space-x-2">
                <button
                  onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                  disabled={currentPage === 1}
                  className="px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  上一页
                </button>

                <div className="flex items-center space-x-1">
                  {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                    const page = i + 1
                    return (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page)}
                        className={`px-3 py-2 text-sm rounded-lg ${currentPage === page
                            ? 'bg-blue-600 text-white'
                            : 'border border-gray-300 hover:bg-gray-50'
                          }`}
                      >
                        {page}
                      </button>
                    )
                  })}
                </div>

                <button
                  onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                  disabled={currentPage === totalPages}
                  className="px-3 py-2 text-sm border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  下一页
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
